package com.dtkavin.threads;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by john on 10/3/16.
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {

        final ReadWrite rw = new ReadWrite();

        new Thread(new Runnable() {
            public void run() {
                System.out.println(rw.read());
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                String data = "this is a demo";
                rw.write(data);
            }
        }).start();
    }


    static class ReadWrite {
        private String data = "init data";
        private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

        public String read() {
            try {
                rwLock.readLock().lock();
                return data;
            } finally {
                rwLock.readLock().unlock();
            }
        }

        public void write(String data) {
            try {
                rwLock.writeLock().lock();
                this.data = data;
            } finally {
                rwLock.readLock().unlock();
            }
        }
    }
}
